﻿using System;
using System.Drawing;
using System.Runtime.InteropServices;

namespace QAQ
{
    class MouseCtrl
    {
        public void MoveRelatedToProcess(IntPtr hwnd, int x, int y)
        {
            int mx = 0, my = 0;
            GetWindowPos(hwnd, ref mx, ref my);
            System.Windows.Forms.Cursor.Position = new System.Drawing.Point((mx + x), (my + y));
        }

        private void GetWindowPos(IntPtr hWnd, ref int x, ref int y)
        {
            if (hWnd == IntPtr.Zero)
            {
                return;
            }
            IntPtr hWndParent = USER32.GetParent(hWnd);
            Rectangle rect = new Rectangle();

            USER32.MapWindowPoints(hWnd, hWndParent, ref rect, 1);
            var point = rect.Location;
            x = point.X;
            y = point.Y;
        }

        private class USER32
        {
            [DllImport("user32.dll")]
            public static extern IntPtr FindWindow(String sClassName, String sAppName);
            [DllImport("user32", ExactSpelling = true, SetLastError = true)]
            internal static extern int MapWindowPoints(IntPtr hWndFrom, IntPtr hWndTo, [In, Out] ref Rectangle rect, [MarshalAs(UnmanagedType.U4)] int cPoints);
            [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
            public static extern IntPtr GetParent(IntPtr hWnd);
        }    
    }
}
